package org.activequant.core.mappings;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.activequant.core.domainmodel.InstrumentSpecification;
import org.activequant.core.domainmodel.Symbol;
import org.activequant.util.tools.ResourceLocator;

/**
 * File mapping strategy.<br>
 * An implementation of the IInstrumentSpecificationMapper which initializes from a property file. Holds the following associated variables:
 * <ul>
 * <li>mapping(Map&lt;String,String&gt;)</li>
 * <li>vendor(String)</li>
 * </ul>
 * <br>
 * <b>History:</b><br>
 *  - [20.01.2008] Created (Erik Nijkamp)<br>
 *
 *  @author Erik Nijkamp
 */
public class FileMapper implements IInstrumentSpecificationMapper {
	/**
	 * private Map&lt;String, String&gt; mapping = new HashMap&lt;String, String&gt;();
	 */
	private Map<String, String> mapping = new HashMap<String, String>();
	/**
	 * private String vendor;
	 */
	private String vendor;
	/**
	 * constructs a FileMapper(IInstrumentSpecificationMapper implementation) using the properties from the property file
	 * found at the given file(String) location.<br/>
	 * Uses the <strong>vendor</strong> property value to set its associated vendor(String). Maps the other properties into
	 * its associated mapping(Map&lt;String,String&gt;)
	 * @param file
	 * @throws Exception
	 */
	public FileMapper(String file) throws Exception {
		// get parameters
		Properties props = ResourceLocator.loadProperties(file);
		vendor = props.getProperty("vendor");		
		for(Object obj : props.keySet()) {
			// get key and value
			String key = (String) obj;
			if(key.equals("vendor")) continue;
			String value = props.getProperty(key);
			// add
			mapping.put(key, value);			
		}
	}
	/**
	 * if the name(String) of the symbol(Symbol) of the given external(InstrumentSpecification) is a <strong>key</strong>
	 * into the associated mapping(Map&lt;String,String&gt;), it returns a copy of the given external(InstrumentSpecification)
	 * whose vendor(String) is set with the associated vendor(String) and symbol(Symbol) whose name(String) is the value
	 * of that <strong>key</strong>.<br/>
	 * Otherwise (if that <strong>key</strong> didn't exist) returns the given external(InstrumentSpecification) unchanged.
	 */
	public InstrumentSpecification mapToInternal(InstrumentSpecification external) {
		// find mapping
		String original = external.getSymbol().toString();
		if(mapping.containsKey(original)) {
			external = new InstrumentSpecification(external);
			String target = mapping.get(original);
			external.setSymbol(new Symbol(target));
			external.setVendor(vendor);
		}
		return external;
	}

}
